import copy
import time
from utils.conf import Response
from rest_framework.views import APIView
from ChatGPTServer.settings import formatResponseData, interfaces
from utils.taskTools import TaskPoolExecutor, Task


class Scheduler(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = []
    # 局部(本视图有效)权限类
    permission_classes = []

    def post(self, request, *args, **kwargs):
        """
        接口调度器
        """
        data = copy.deepcopy(formatResponseData)
        try:
            question = request.data.get("question")

            # 异常拦截
            if not question:
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            # 执行 请求分发器
            answer = requestDistributor(request=request)

            data["data"]["answer"] = answer
            return Response(data=data)

        except Exception as e:
            return Response(data=data, responseMsg="ServerError",
                            loggerMsg=f"请求处理失败: {e}", isError=True)


def requestDistributor(request):
    """
    请求 分发器
    将请求分别异步请求 至所有 接口
    返回最先响应的接口内容
    """
    question = request.data.get("question")
    taskPoolExecutor = TaskPoolExecutor(maxThreadSize=len(interfaces),
                                        taskPoolName=f"请求分发器，question={question}")

    # 请求结果
    answer = [None]

    # 分发异步请求
    for interface in interfaces:
        def fun():
            response = interface.post(request=request).data
            if response["code"] == 200:
                answer[0] = response["data"]["answer"]

        task = Task(fun=fun, taskName=f"请求任务：{interface.__class__.__name__}接口")
        taskPoolExecutor.putAndRunTask(task=task)

    # 阻塞，直到得到结果
    while (not answer[0]) and taskPoolExecutor.taskPoolSize():
        time.sleep(0.1)

    del taskPoolExecutor

    return answer[0]
